package com.kfm.pm;

import java.sql.*;

public class Test {

    public static void main(String[] args) {
        String username = "test";
        String password = "test' or '1' = '1";
        String sql = "select * from users where username = '" + username + "' and password = '" + password + "'";

        System.out.println(sql);
        // ? 为占位符  setObject()  将占位符 替换成具体的值
        // 更加方便 不需要再拼接字符串
        // 防止 sql 注入
        String sql1 = "select * from users where username = ? and password = ?";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/manager", "root", "");
             // 获取执行sql的对象
//             Statement stat = conn.createStatement();
             PreparedStatement prepared = conn.prepareStatement(sql1);) {
//            ResultSet resultSet = stat.executeQuery(sql);
            prepared.setObject(1, username); // 将第一个占位符 替换成 username
            prepared.setObject(2, password); // 将第二个占位符 替换成 password
            ResultSet resultSet = prepared.executeQuery();

            while (resultSet.next()) {
                System.out.println(resultSet.getObject(1));
                System.out.println(resultSet.getObject(2));
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }
}
